package com.nuanshui.heatedloan.userinfo.service;
/**
 * 处理用户token相关的业务逻辑
 */

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.aliases.IdTypeHandler;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.DubboCacheRegion;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.dubbo.extension.cache.manager.DubboCacheManager;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.middleware.rabbitmq.message.RabbitmqMessage;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserTokenMapper;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.model.SafeToken;
import com.nuanshui.heatedloan.userinfo.model.UserDeviceToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service("userTokenService")
@Transactional(readOnly=true,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
public class UserTokenServiceImpl extends CommonServiceImpl implements UserTokenService {
	
	@Autowired
	private UserTokenMapper userTokenMapper;

	private Logger logger  = LoggerFactory.getLogger(UserTokenServiceImpl.class);
	
	@Autowired
	private RabbitmqMessageSender rabbitmqMessageSender;
	
	/**
	 * 根据用户的id 和用户的设备类型选择userToken
	 * @param 
	 * @author guohao
	 * @date 2015年4月15日 下午4:21:17
	 */
	@Override
	public List<UserDeviceToken> selectByUserIdAndDeviceType(String userId,String deviceType) {
		return userTokenMapper.selectByUserIdAndDeviceType(userId, deviceType);
	}

	/**
	 * 增加一条记录
	 * @param 
	 * @author guohao
	 * @date 2015年4月15日 下午4:21:08
	 */
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void addUserToken(UserDeviceToken userDeviceToken) {
		userTokenMapper.addUserToken(userDeviceToken);
	}

	/**
	 * 更新用户的userToken
	 * @param 
	 * @author guohao
	 * @date 2015年4月15日 下午4:46:17
	 */
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void updateUserToken(UserDeviceToken userDeviceToken) {
		userTokenMapper.updateUserToken(userDeviceToken);
	}

	/**
	 * 删除用户的某个设备
	 * @param 
	 * @author guohao
	 * @date 2015年4月15日 下午4:58:17
	 */
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void deleteByUserIdAndDeviceType(Long userId,String deviceToken) {
		userTokenMapper.deleteUserTokenByUserIdAndDeviceType(userId, deviceToken);
	}

	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void deleteByDeviceTokenAndDeviceType(String deviceToken,String deviceType) {
		userTokenMapper.deleteByDeviceTokenAndDeviceType(deviceToken, deviceType);
	}

	@Override
	public List<HashMap<String, Object>> selectUserTokensByUserIds(List<String> userIds,String userId,String type,String clientType) {
		return userTokenMapper.selectUserTokensByUserIds(userIds,userId,type,clientType);
	}

	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void setUserIdNullByUserId(String userId) {
		userTokenMapper.setuserIdNullByUserId(userId);
	}
	
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void updateDeviceToken(String deviceToken, String deviceType,
			String version, String userId) {
		if (!StringUtils.isEmpty(userId)
				&& !StringUtils.isEmpty(deviceToken)
				&& !StringUtils.isEmpty(deviceType)) {
			this.deleteByDeviceTokenAndDeviceType(deviceToken, deviceType);
			this.setUserIdNullByUserId(userId);
			// 说明存在这个token不存在
			UserDeviceToken userDeviceToken = new UserDeviceToken();
			userDeviceToken.setUserId(IdTypeHandler.decode(userId));
			userDeviceToken.setDeviceToken(deviceToken);
			userDeviceToken.setDeviceType(deviceType);
			userDeviceToken.setCreatedAt(new Date());
			userDeviceToken.setUpdatedAt(new Date());
			userDeviceToken.setVersion(version);
			this.addUserToken(userDeviceToken);
		}
	}

	@Autowired
	private DubboCacheManager dubboCacheManager;

	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void saveSafeToken(SafeToken safeToken) {
		userTokenMapper.saveSafeToken(safeToken);

		dubboCacheManager.put(DubboCacheRegion.CACHE_CONSTANT_USER_SAFETOKEN,1,safeToken);
	}

	@Override
	public Integer loadTokenCount(String token) {
		return userTokenMapper.loadTokenCount(token);
	}

	@Override
	public boolean validSafeToken(String safeToken) {
		Object value = dubboCacheManager.get(DubboCacheRegion.CACHE_CONSTANT_USER_SAFETOKEN,safeToken);
		if (value != null) return true;
		Integer count = loadTokenCount(safeToken);
		if (count > 0) {
			dubboCacheManager.put(DubboCacheRegion.CACHE_CONSTANT_USER_SAFETOKEN,1,safeToken);
			return true;
		}
		return false;
	}

	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void saveUserSafeToken(String safeToken, String userId) {
		userTokenMapper.saveUserSafeToken(safeToken, userId);
	}

	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void delUserSafeToken(String safeToken, String userId) {
		userTokenMapper.delUserSafeToken(safeToken, userId);
	}

	@Override
	public void addUserTokenOnAsyn(String deviceToken, String deviceType,
			String version, String userId) {
		if (StringUtils.isNotEmpty(userId)
				&& StringUtils.isNotEmpty(deviceToken)
				&& StringUtils.isNotEmpty(deviceType)) {
			LogUtil.info(logger, "-----------------------发送保存用户 token 的消息-----------------------");
			HashMap<String, String> map = Maps.newHashMap();
			map.put("userId", userId);
			map.put("deviceToken", deviceToken);
			map.put("deviceType", deviceType);
			map.put("version", version);
			RabbitmqMessage rabbitmqMessage = new RabbitmqMessage();
			rabbitmqMessage.setQueue(RabbitMqQueue.USER_TOKEN_SAVE_MSG);
			rabbitmqMessage.setBody(JSON.toJSONString(map));
			rabbitmqMessageSender.send(rabbitmqMessage);
		}
	}

	@Override
	public UserDeviceToken loadUserTokenByUserId(String userId) {
		return userTokenMapper.loadUserTokenByUserId(userId);
	}
}